/*
 * Copyright (c) 2018, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.admin.sys.config;

import java.util.Objects;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.cory.boot.config.MybatisPlusMetaObjectHandler;
import com.cory.boot.domain.bean.Principal;

/**
 * @author guilu
 * @date 2018年12月3日
 */
@Component
public class AdminMetaObjectHandler extends MybatisPlusMetaObjectHandler {
    
    @Autowired
    private AdminService adminService;

    private static String CREATE_USER = "createUser";
    private static String MODIFY_USER = "modifyUser";
    
    @Override
    public void insertFill(MetaObject metaObject) {
        super.insertFill(metaObject);
        
        Principal principal = adminService.getPrincipal();
        if (principal == null) {
            return;
        }
        
        Object createUser = getFieldValByName(CREATE_USER, metaObject);
        if (Objects.isNull(createUser)) {
            this.setFieldValByName(CREATE_USER, principal.getUserId(), metaObject);
        }
        Object modifyUser = getFieldValByName(MODIFY_USER, metaObject);
        if (Objects.isNull(modifyUser)) {
            this.setFieldValByName(MODIFY_USER, principal.getUserId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        super.updateFill(metaObject);
        
        Principal principal = adminService.getPrincipal();
        if (principal == null) {
            return;
        }
        
        Object modifyUser = getFieldValByName(MODIFY_USER, metaObject);
        if (Objects.isNull(modifyUser)) {
            this.setFieldValByName(MODIFY_USER, principal.getUserId(), metaObject);
        }
    }

}
